import React, { useEffect, useMemo, useState } from "react";
import { Button, Tree, Space, Modal, message, Form, Input, Table } from 'antd'; 
import { DataNode } from "antd/es/tree";
import { userTypes } from "@/constants/types";
import { fetchDeptTree, addInnerUser, updateInnerUser, deleteMenu, addDept, fetchInnerUserList, enableInnerUser, disableInnerUser, resetInnerUserPassword } from '../services';
import '../index.less';
import { useComponentDidMount } from "@/hooks";
import { isEmptyObj } from "@/utils/util";
import UserUpdateModal from "../modals/UserUpdateModal";
import DeptUpdateModal from "../modals/DeptUpdateModal";
import { useRequest } from "ahooks";
import { PlusOutlined } from "@ant-design/icons";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";


const {Item} = Form;
const initPager = {
  pageNum: 1,
  pageSize: 20
}

const LeftDeptTree = ({ onSelect, onSetTree }) => {
  const [treeData, setTreeData] = useState<DataNode []>([]);
  const [expandedKeys, setExpandedKeys] = useState<string []>([]);
  const [selectRow, setSelectRow] = useState<DataNode | null>(null);
  const [searchValue, setSearchValue] = useState<string>('');
  const [visible, setVisible] = useState(false);

  const {loading: addLoading, runAsync: addApi} = useRequest(addDept, {manual: true});

  console.log('setSearchValue', setSearchValue);

  const onExpand: any = (keys: string []) => {
    setExpandedKeys(keys);
  }

  const fetchDeptTreeApi = async () => {
    const res = await fetchDeptTree();
    if (res?.code === '0' && res?.data?.length > 0) { 
      // 所有展开的节点
      const expandedList: string [] = [];
      const mapTree = (arr: any []) => {
        arr.forEach(element => {
          expandedList.push(element.id);
          if (element?.children?.length > 0) {
            mapTree(element?.children);
          }
        });
      }
      // 递归枚举树节点
      mapTree(res?.data);
      setTreeData(res?.data);
      setExpandedKeys(expandedList);
      setSelectRow(res?.data?.[0]);
      onSelect(res?.data?.[0]);
      onSetTree(res?.data);
    }
  }

  const contentProps = {
    visible,
    title: '新增部门',
    parentRow: selectRow,
    loading: addLoading,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await addApi(params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        fetchDeptTreeApi();
      }
    },
  }

  const handleAdd = () => {
    setVisible(true);
  }

  const resultTree = useMemo(() => {
    const loop = (data) =>
      data.map((item) => {
        const strTitle = item.name;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return {
            name: title,
            id: item.id,
            children: loop(item.children),
          };
        }
        return {
          name: title,
          id: item.id,
        };
      });
    return searchValue?.trim() ? loop(treeData) : treeData;
  }, [searchValue, JSON.stringify(treeData)]);

  useComponentDidMount(() => {
    fetchDeptTreeApi();
  });



  return (
    <>
      <div className="tree-wrapper">
        <div className="tree-search">
          <Input.Search className="search-input" onChange={e => setSearchValue(e.target.value)} />
          <Button onClick={handleAdd} type="primary" icon={<PlusOutlined />} />
        </div>
        <Tree
          expandedKeys={expandedKeys}
          selectedKeys={selectRow ? [selectRow?.id] : []}
          onSelect={(selected, {node}) => {
            setSelectRow(node);
            onSelect(node)
          }} 
          treeData={resultTree}
          onExpand={onExpand}
          fieldNames={{
            title: "name",
            key: "id",
            children: "children"
          }}
        />
      </div>
      {visible && <DeptUpdateModal {...contentProps} />}
    </>
  );
}

const RightUserTable = ({ node, treeData }: {node: any, treeData: any []}) => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({...initPager, total: 0});

  const [currentRow, setCurrentRow] = useState<userTypes | null>(null);
  const [visible, setVisible] = useState(false);
  const {loading: addLoading, runAsync: addApi} = useRequest(addInnerUser, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateInnerUser, {manual: true});

  const search = async (params: any) => {
    const res = await fetchInnerUserList({
      ...params,
      deptId: node?.id
    });
    const {data, total} = res || {};
    setDataSource(data || []); 
    setPagination({pageNum: params?.pageNum, pageSize: params?.pageSize, total: total});
  }

  const contentProps = {
    title: currentRow ? '编辑用户' : '新增用户',
    visible,
    currentRow,
    selectNode: node,
    treeData: treeData,
    loading: currentRow ? updateLoading : addLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
        search(initPager);
      }
    },
  }

  const handleSearch = () => {
    const res = form.getFieldsValue();
    search({
      ...initPager,
      ...res
    });
  }
  const handleReset = () => {
    form.resetFields();
    search(initPager);
  }
  const handleAdd = () => {
    setVisible(true);
  }
  const handleEdit = (record: userTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleEnable = (record: userTypes) => {
    Modal.confirm({
      title: '是否确定启用此用户',
      onOk: () => {
        enableInnerUser({id: record.id}).then(() => {
          search(initPager);
        })
      }
    });
  }
  const handleDisable = (record: userTypes) => {
    Modal.confirm({
      title: '是否确定禁用此用户',
      onOk: () => {
        disableInnerUser({id: record.id}).then(() => {
          search(initPager);
        })
      }
    });
  }
  const handleResetPwd = (record: userTypes) => {
    Modal.confirm({
      title: '是否确定重置此用户的登录密码',
      onOk: () => {
        resetInnerUserPassword({id: record.id}).then((res) => {
          if (res?.code === '0') {
            message.success('密码重置成功!');
            search(initPager);
          } else {
            message.warning('操作失败!');
          }
        })
      }
    });
  }


  const columns = [
    { 
      title: '员工姓名',
      dataIndex: 'realName',
    },
    { 
      title: '状态',
      dataIndex: 'status',
      render: (_: number, record: any) => <XlTableDictColumn  type="disabledStatus" value={record?.status} />
    },
    { 
      title: '手机号',
      dataIndex: 'mobile',
    },
    { 
      title: '登录账户',
      dataIndex: 'userName',
    },
    { 
      title: '部门负责人',
      dataIndex: 'isLeader',
      render: (_: number, record: any) => <XlTableDictColumn  type="yesOrNo" value={record?.isLeader} />
    },
    { 
      title: '角色',
      dataIndex: 'roleName',
    },
    { 
      title: '创建时间',
      dataIndex: 'createTime',
    },
    { 
      title: '创建人',
      dataIndex: 'createBy',
    },
    { 
      title: '操作',
      dataIndex: 'options',
      width: 200,
      render: (_, record: userTypes) => {
        return (
          <Space>          
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleResetPwd(record)}>重置密码</Button>
            {
              +record?.status === 0 && <Button type="link" onClick={() => handleDisable(record)}>禁用</Button>
            }
             {
              +record?.status === 1 && <Button type="link" onClick={() => handleEnable(record)}>启用</Button>
            }
          </Space>
        );
      }
    },
  ];
  
  useEffect(() => {
    if (!isEmptyObj(node)) {
      form.resetFields();
      search(initPager);
    }
  }, [node?.id]);

  return (
    <>
      <div className="table-wrapper">
        <div className="form-wrapper">
          <Button type="primary" onClick={handleAdd}>新建用户</Button>
          <Form form={form} layout="inline">
            <Item label="员工姓名" name="realName">
              <Input />
            </Item>
            <Item label="角色" name="roleName">
              <Input />
            </Item>
            <Item>
              <Space direction="horizontal">
                <Button type="primary" onClick={handleSearch}>查询</Button>
                <Button type="primary" onClick={handleReset}>重置</Button>
              </Space>
            </Item>
          </Form>
        </div>
        <Table
          bordered
          rowKey="id"
          columns={columns}
          dataSource={dataSource}
          pagination={{
            ...pagination,
            showTotal: total => `共 ${total} 条`,
            onChange: (pageNum, pageSize) => {
              const values = form.getFieldsValue();
              search({
                ...values,
                pageNum,
                pageSize
              });
            }
          }}  
        />        
      </div>
      {visible && <UserUpdateModal {...contentProps} />}
    </>
  );
}

const UserManage = () => {
  const [node, setNode] = useState<any | null>(null);
  const [treeData, setTreeData] = useState<any []>([]);

  const onSelect = (node: DataNode) => {
    setNode(node);
  }
  const onSetTree = (list) => {
    setTreeData(list);
  }

  return (
    <>
      <div className="column-wrapper">
        <LeftDeptTree 
          onSelect={onSelect}
          onSetTree={onSetTree}
        />
        <RightUserTable node={node} treeData={treeData} />
      </div>
    </>
  );
}
export default UserManage;